package com.ap.core.email.velocity;


import org.apache.velocity.VelocityContext;
import org.apache.velocity.app.Velocity;
import org.apache.velocity.app.VelocityEngine;
import org.apache.velocity.exception.MethodInvocationException;
import org.apache.velocity.exception.ParseErrorException;
import org.apache.velocity.exception.ResourceNotFoundException;

import org.springframework.ui.velocity.VelocityEngineUtils;

import java.io.IOException;
import java.io.Reader;
import java.io.StringWriter;
import java.util.Iterator;
import java.util.Map;
import java.util.Properties;
import java.util.Set;


/**
 * This interacts with Velocity to generate content from the velocity template.
 */
public class VelocityContentGenerator {

    /**
     * Generate stream as StringWriter after processing velocity template
     * 
     * @param template - template
     * @param parameters - to put into the template context
     * @param loggingClass- for Velocity to log output to
     * @return a stream
     */
    public StringWriter generate(Reader template, Map<String, String> parameters,Class loggingClass) {

        Properties props = new Properties();

        Velocity.init(props);

        VelocityContext context = new VelocityContext();

        Set<String> keys = parameters.keySet();
        Iterator<String> it = keys.iterator();
        String key;
        while (it.hasNext()) {
            key = it.next();
            context.put(key, parameters.get(key));
        }

        StringWriter writer = new StringWriter();

        try {
            Velocity.evaluate(context, writer, loggingClass.getName(), template);
        } catch (ParseErrorException e) {
            throw new InvalidVelocityTemplateException(e.getMessage(), e);
        } catch (MethodInvocationException e) {
            throw new VelocityMethodInvocationException(e.getMessage(), e);
        } catch (ResourceNotFoundException e) {
            throw new VelocityResourceNotFoundException(e.getMessage(), e);
        }

        writer.flush();
        try {
            writer.close();
        } catch (IOException e) {
            throw new VelocityIOException(e.getMessage(), e);            
        }
        return writer;

    }


    public String mergeTemplate(String templatePath, Map<String, Object> parameters, VelocityEngine velocityEngine, String encoding){

        return   VelocityEngineUtils.mergeTemplateIntoString(velocityEngine, templatePath, encoding, parameters);
    }
}
